package main

import (
	"github.com/micro/go-web"
	"github.com/micro/cli"
	"github.com/ngaut/log"
	"global/core"
	"net/http"
	"fmt"
)

const (
	appName = "app"
	defaultConfigFile = "../../config/config.toml"
)

var configFile string

func main() {

	service := web.NewService(
		web.Name("go.micro.web.app"),
		web.Version("latest"),
		web.Flags(cli.StringFlag{
			Name: 		"config",
			Usage: 		"Custom server config file.",
		}),
	)

	if err := initService(service); err != nil {
		log.Fatalf("Fatal error: %s", err)
	}

	h := NewHandler(service, initContext())
	h.RegisterHandler("/coin/search/tag", h.OnHandleCoinSearchTag)
	h.RegisterHandler("/coin/search", h.OnHandleCoinSearch)
	h.RegisterHandler("/coin/detail", h.OnHandleGetCoinDetail)
	// 添加删除关注的币种
	h.RegisterHandler("/coin/like/action", h.OnHandleAddCoinToSearch)
	h.RegisterHandler("/exchange/detail", h.OnHandleGetExchangeDetail)
	h.RegisterHandler("/analysis/exchange/ticker", h.OnHandleGetAnalysisTicker)

	service.HandleFunc("/static/", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Println(request.URL.Path[1:])
		http.ServeFile(writer, request, "../" + request.URL.Path[1:])
	})

	if err := service.Run(); err != nil {
		fmt.Println("err:", err)
		log.Fatalf("Fatal error: server run failed, %s", err)
	}
}

func initContext() *core.Context {
	ctx := core.NewContext()
	ctx.Bootstrap(configFile, appName).Initialize()
	return ctx
}

// 初始化
func initService(service web.Service) error {
	return service.Init(
		web.Action(func(ctx *cli.Context) {
			configFile = ctx.String("config")
			if configFile == "" {
				configFile = defaultConfigFile
			}
		}),
	)
}